package controller

import (
	"mini-app/internal/app/admin/service"
	"strconv"
	"strings"

	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type PromotionChannel struct{}

// Add 新增渠道
func (PromotionChannel) Add(c *gin.Context) {
	var params struct {
		Name     string `json:"name"`
		RobotIDs string `json:"robot_ids"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	robotIDs := []string{}
	if params.RobotIDs != "" {
		robotIDs = strings.Split(params.RobotIDs, ",")
	}
	channelID, err := service.PromotionChannel{}.Add(c.Request.Context(), params.Name, robotIDs)
	response.JSON(c, gin.H{
		"id": channelID,
	}, err)
}

// Update 更新渠道
func (PromotionChannel) Update(c *gin.Context) {
	var params struct {
		ID       string `json:"id"`
		Name     string `json:"name"`
		RobotIDs string `json:"robot_ids"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	robotIDs := []string{}
	if params.RobotIDs != "" {
		robotIDs = strings.Split(params.RobotIDs, ",")
	}
	err := service.PromotionChannel{}.Update(c.Request.Context(), params.ID, params.Name, robotIDs)
	response.JSON(c, nil, err)
}

// Delete 删除渠道
func (PromotionChannel) Delete(c *gin.Context) {
	var params struct {
		ID string `json:"id"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	err := service.PromotionChannel{}.Delete(c.Request.Context(), params.ID)
	response.JSON(c, nil, err)
}

// List 渠道列表
func (PromotionChannel) List(c *gin.Context) {
	name := c.Query("name")
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	list, total := service.PromotionChannel{}.List(c.Request.Context(), name, page, limit)
	response.JSON(c, gin.H{
		"list":  list,
		"total": total,
	}, nil)
}

// AssignedRebotIDs 已分配的设备id
func (PromotionChannel) AssignedRebotIDs(c *gin.Context) {
	channelID := c.Query("channel_id")
	robotIDs, err := service.PromotionChannel{}.AssignedRebotIDs(c.Request.Context(), channelID)
	response.JSON(c, gin.H{
		"robot_ids": robotIDs,
	}, err)
}
